<template>
	<view class="w-[100%] flex flex-col relative">
		<image src="@/static/images/index_bg/bg_index.png" placeholder
			class="w-[100%] h-[396rpx] z-[-1] absolute top-0"></image>
		<up-navbar title="" :autoBack="false" bgColor="rgba(255,255,255,0)">
			<template #left>
				<text class="text-[34rpx] text-[#000] font-[500]">宠物定位</text>
			</template>
		</up-navbar>
		<view :style="{ paddingTop: menuButtonInfoBottom + 'px' }" class="mt-[34rpx] flex-1 w-[100%] relative">
			<view class="rounded-t-[64rpx] " style="overflow: hidden;">
				<map class="w-[750rpx] h-[1350rpx]" 
					:latitude="latitude" 
					:longitude="longitude"
					:markers="markers"
					:polyline="polyline"
					:circles="circles"
					:show-location="true">
				</map>
			</view>
			<view style="background: rgba(0, 0, 0, 0.22);"
				class="absolute top-[200rpx] left-[30rpx] w-[452rpx] rounded-[260rpx]">
				<view class="h-[80rpx] flex items-center text-[28rpx] text-[#ffffff] pl-[84rpx]" @click="listShow = !listShow">
					<text>{{ selectedFence ? selectedFence.name : '请选择围栏' }}</text>
					<view class="absolute right-[30rpx]">
						<image src="@/static/images/img/xia-1.png" class="w-[36rpx] h-[20rpx]"></image>
					</view>
				</view>
				<view v-show="listShow" style="background: rgba(0, 0, 0, 0.22);"
					class="absolute rounded-[50rpx] p-[20rpx] h-[600rpx] overflow-hidden top-[90rpx] w-[100%] ">
					<z-paging :empty-view-img="'213'" :empty-view-error-text="`对不起,页面走丢了\n请刷新试试`"
						ref="paging" v-model="fenceList" @query="queryList"
						loading-more-theme-style="white"
						refresher-theme-style="white"
						:loading-more-title-custom-style="{color:'#fff'}"
						:fixed="false" width="100%" height="100%">
						<view v-for="(item, index) in fenceList" :key="item.id" 
							class="w-[100%] mb-[10rpx] text-[#fff] text-[30rpx] pb-[10rpx] overflow-hidden whitespace-nowrap text-ellipsis"
							@click="selectFence(item)">
							{{ item.name }}
						</view>
					</z-paging>
				</view>
			</view>
			<view @click="push('/pages_cw/setupfence/setupfence')" class=" absolute top-[200rpx] right-[30rpx]">
				<image src="@/static/images/img/shezhi.png" class="w-[208rpx] h-[80rpx] relative "></image>
				<view
					class="absolute top-[22rpx] left-[76rpx] text-[24rpx] text-[#000000] font-[600] font-[PingFangSC]">
					围栏设置
				</view>
			</view>

			<!-- 显示位置信息 -->
			<!-- <view v-if="locationInfo" class="absolute top-[300rpx] left-[30rpx] bg-white rounded-[20rpx] p-[20rpx] max-w-[600rpx]">
				<text class="text-[24rpx] text-[#333]">当前位置：</text>
				<text class="text-[24rpx] text-[#666]">经度 {{longitude}}，纬度 {{latitude}}</text>
			</view> -->

			<!-- 底部按钮 -->
			<view class="absolute bottom-[30rpx] left-[40rpx]">
				<image src="@/static/images/game_logo/xiangling.png" class="w-[172rpx] h-[80rpx]"></image>
			</view>
			<view class="absolute bottom-[30rpx] left-[224rpx]">
				<image src="@/static/images/game_logo/shangbao.png" class="w-[172rpx] h-[80rpx]"></image>
			</view>

			<!-- 围栏开启按钮 -->
			<view v-if="selectedFence && fenceStatus === 0" @click="toggleFenceStatus(1)" class="absolute bottom-[30rpx] right-[40rpx]">
				<image src="@/static/images/game_logo/kq.png" class="w-[302rpx] h-[80rpx]"></image>
			</view>

			<!-- 围栏关闭按钮 -->
			<view v-if="selectedFence && fenceStatus === 1" @click="toggleFenceStatus(0)" class="absolute bottom-[124rpx] right-[40rpx]">
				<image src="@/static/images/game_logo/gb.png" class="w-[302rpx] h-[80rpx]"></image>
			</view>
		</view>
	</view>
	<tabBar />
</template>
<script setup>
import {
	onLoad, onShow
} from '@dcloudio/uni-app'
import {
	ref
} from 'vue'
import{ getFenceList ,closeFence ,getTrackList} from '@/api/pet.js';
import useUserStore from '@/store/modules/user';
const userStore = useUserStore();
// 基础UI相关变量
const menuButtonInfoBottom = ref(90) // 胶囊按钮信息

// 地图相关变量
const latitude = ref(39.909) // 纬度
const longitude = ref(116.39742) // 经度
const locationInfo = ref(false) // 是否显示位置信息
const markers = ref([]) // 地图标记点

// 围栏相关变量
const fenceList = ref([]);
const listShow = ref(false);
const paging = ref(null);
const selectedFence = ref(null); // 当前选中的围栏
const circles = ref([]); // 添加围栏圆形区域数据
const fenceStatus = ref(0); // 围栏状态：0-关闭，1-开启

// 页面加载函数
onLoad(() => {
	menuButtonInfoBottom.value = uni.getMenuButtonBoundingClientRect().bottom || 90;
	console.log(uni.getMenuButtonBoundingClientRect());

	// 页面加载时检查权限并获取位置
	requestLocationPermission();
	
	// 初始化围栏列表
	if (paging.value) {
		paging.value.reload();
	}
});

// 获取围栏列表数据
const queryList = async (pageNum, pageSize) => {
	try {
		const from = {
			pageNum: pageNum,
			pageSize: pageSize,
            
		};
		const { rows } = await getFenceList(from);
		paging.value.complete(rows);
		
		// 获取围栏列表后，更新所有围栏显示
		updateAllFences(rows);
	} catch (e) {
		console.log('报错=>', e);
		//TODO handle the exception
		paging.value.complete(false);
	}
};

// 更新所有围栏显示
const updateAllFences = (fences) => {
	if (!fences || fences.length === 0) {
		console.log('没有围栏数据');
		return;
	}
	
	// 更新所有围栏的圆形区域
	updateAllCircles(fences);
	
	// 更新所有围栏的标记点
	updateAllMarkers(fences);
	
	// 如果没有选中围栏，则将地图中心设置为第一个围栏的位置
	if (!selectedFence.value && fences.length > 0) {
		latitude.value = fences[0].latitude;
		longitude.value = fences[0].longitude;
	}
};

// 更新所有围栏的圆形区域
const updateAllCircles = (fences) => {
	if (!fences || fences.length === 0) {
		circles.value = [];
		return;
	}
	
	// 创建所有围栏的圆形区域数组
	const allCircles = [];
	
	fences.forEach(fence => {
		if (fence && fence.latitude && fence.longitude && fence.radius) {
			// 将千米转换为米
			const radiusInMeters = Number(fence.radius) * 1000;
			
			// 为每个围栏创建一个圆形区域
			allCircles.push({
				latitude: fence.latitude,
				longitude: fence.longitude,
				color: fence.id === (selectedFence.value?.id) ? '#FFFF0088' : '#1E90FF88', // 选中的围栏用黄色，其他用蓝色
				fillColor: fence.id === (selectedFence.value?.id) ? '#FFFF0044' : '#1E90FF44', // 填充色更透明
				radius: radiusInMeters,
				strokeWidth: fence.id === (selectedFence.value?.id) ? 2 : 1 // 选中的围栏线宽更大
			});
		}
	});
	
	circles.value = allCircles;
	console.log('设置所有围栏圆形区域成功:', circles.value);
};

// 更新所有围栏的标记点
const updateAllMarkers = (fences) => {
	if (!fences || fences.length == 0) {
		// 如果没有围栏，只显示当前位置
		markers.value = [{
			id: 0,
			iconPath: 'https://falvren.oss-cn-beijing.aliyuncs.com/20250606153630cbb33.png',
			latitude: latitude.value,
			longitude: longitude.value,
			width: 32,
			height: 32,
			callout: {
				content: '当前位置',
				color: '#000000',
				fontSize: 14,
				borderRadius: 4,
				bgColor: '#ffffff',
				padding: 8,
				display: 'ALWAYS'
			}
		}];
		return;
	}
	
	// 创建所有围栏的标记点数组
	const allMarkers = [];
	
	// 添加当前位置标记
	allMarkers.push({
		id: 0,
		iconPath: 'https://falvren.oss-cn-beijing.aliyuncs.com/20250606153630cbb33.png',
		latitude: latitude.value,
		longitude: longitude.value,
		width: 32,
		height: 32,
		callout: {
			content: '当前位置',
			color: '#000000',
			fontSize: 14,
			borderRadius: 4,
			bgColor: '#ffffff',
			padding: 8,
			display: 'ALWAYS'
		}
	});
	
	// 为每个围栏添加标记点
	fences.forEach((fence, index) => {
		if (fence && fence.latitude && fence.longitude) {
			allMarkers.push({
				id: index + 1,
				iconPath: 'https://falvren.oss-cn-beijing.aliyuncs.com/20250606153630cbb33.png',
				latitude: fence.latitude,
				longitude: fence.longitude,
				width: 32,
				height: 32,
				callout: {
					content: fence.name || `围栏${index + 1}`,
					color: '#000000',
					fontSize: 14,
					borderRadius: 4,
					bgColor: '#ffffff',
					padding: 8,
					display: 'ALWAYS'
				}
			});
		}
	});
	
	markers.value = allMarkers;
};

// 选择围栏
const selectFence = (fence) => {
	selectedFence.value = fence;
	listShow.value = false; // 选择后关闭列表
	
	// 更新地图中心点到围栏位置
	latitude.value = fence.latitude;
	longitude.value = fence.longitude;
	
	// 更新所有围栏显示，突出显示选中的围栏
	updateAllFences(fenceList.value);
	
	// 获取围栏状态
	fenceStatus.value = fence.status || 0;
	
	console.log('选中围栏:', fence);
};
//获取运动轨迹
const polyline = ref([]);

const getgj = async () => {
	const params = {
		uid: userStore.userId,
	};
	try {
		const res = await getTrackList(params);
		console.log("返回的轨迹信息", res);
		
		// 检查是否有轨迹数据
		if (res && res.data && res.data.length > 0) {
			// 提取轨迹点坐标
			const points = res.data.map(item => ({
				latitude: Number(item.la), // 纬度
				longitude: Number(item.lo) // 经度
			}));
			
			// 按时间排序（如果数据中有时间字段）
			// points.sort((a, b) => new Date(a.time) - new Date(b.time));
			
			// 更新轨迹线
			polyline.value = [{
				points: points,
				color: '#FF4500', // 橙红色
				width: 4, // 线宽
				dottedLine: false, // 实线
				arrowLine: true, // 显示箭头
				arrowIconPath: 'car-fill', // 箭头图标
				borderColor: '#FF8C00', // 边框颜色
				borderWidth: 1 // 边框宽度
			}];
			
			// 如果有轨迹点，将地图中心设置为第一个点
			if (points.length > 0) {
				latitude.value = points[0].latitude;
				longitude.value = points[0].longitude;
			}
			
			console.log("轨迹线设置成功", polyline.value);
		} else {
			console.log("没有轨迹数据");
			polyline.value = [];
		}
	} catch (error) {
		console.error("获取轨迹失败:", error);
		uni.showToast({
			title: '获取轨迹失败',
			icon: 'none'
		});
		polyline.value = [];
	}
};
// // 更新围栏圆形区域
// const updateCircles = (fence) => {
// 	console.log('更新围栏圆形区域:', fence);
// 	if (fence && fence.latitude && fence.longitude && fence.radius) {
// 		// 将千米转换为米
// 		const radiusInMeters = Number(fence.radius) * 1000;
// 		console.log('围栏半径(米):', radiusInMeters);
// 		circles.value = [{
// 			latitude: fence.latitude,
// 			longitude: fence.longitude,
// 			color: '#FFFF0088', // 蓝色半透明
// 			fillColor: '#FFFF0088', // 填充色更透明
// 			radius: radiusInMeters,
// 			strokeWidth: 2
// 		}];
// 		console.log('设置围栏圆形区域成功:', circles.value);
// 	} else {
// 		console.log('围栏数据不完整，无法绘制圆形区域');
// 		circles.value = [];
// 	}
// };

// 更新地图标记点
const updateMarkers = (fence = null) => {
	if (fence) {
		// 如果有选中的围栏，显示围栏位置
		markers.value = [{
			id: 1,
			iconPath: 'https://falvren.oss-cn-beijing.aliyuncs.com/20250606153630cbb33.png',
			latitude: fence.latitude,
			longitude: fence.longitude,
			width: 32,
			height: 32,
			callout: {
				content: fence.name || '围栏位置',
				color: '#000000',
				fontSize: 14,
				borderRadius: 4,
				bgColor: '#ffffff',
				padding: 8,
				display: 'ALWAYS'
			}
		}];
	} else {
		// 否则显示当前位置
		markers.value = [{
			id: 1,
			iconPath: 'https://falvren.oss-cn-beijing.aliyuncs.com/20250606153630cbb33.png',
			latitude: latitude.value,
			longitude: longitude.value,
			width: 32,
			height: 32,
			callout: {
				content: '当前位置',
				color: '#000000',
				fontSize: 14,
				borderRadius: 4,
				bgColor: '#ffffff',
				padding: 8,
				display: 'ALWAYS'
			}
		}];
	}
};

// 获取用户当前位置
const getLocation = () => {
	uni.getLocation({
		type: 'gcj02',
		success: (res) => {
			console.log('当前位置的经度：' + res.longitude);
			console.log('当前位置的纬度：' + res.latitude);

			// 更新位置信息
			latitude.value = res.latitude;
			longitude.value = res.longitude;
			locationInfo.value = true;

			// 更新地图标记点
			updateMarkers();

			uni.showToast({
				title: '定位成功',
				icon: 'success'
			});
		},
		fail: (err) => {
			console.log('获取位置失败：', err);
			// 获取位置失败时，检查并请求权限
			requestLocationPermission();
		}
	});
};

// 请求位置权限
const requestLocationPermission = () => {
	uni.authorize({
		scope: 'scope.userLocation',
		success: () => {
			uni.getLocation({
				type: 'gcj02',
				success: (res) => {
					console.log('当前位置的经度：' + res.longitude);
					console.log('当前位置的纬度：' + res.latitude);

					// 更新位置信息
					latitude.value = res.latitude;
					longitude.value = res.longitude;
					locationInfo.value = true;

					// 更新地图标记点
					updateMarkers();

					uni.showToast({
						title: '定位成功',
						icon: 'success'
					});
				},
				fail: (err) => {
					console.log('获取位置失败：', err);
					uni.showToast({
						title: '定位失败，请检查GPS是否开启',
						icon: 'none'
					});
				}
			});
		},
		fail: () => {
			// 授权失败，用户拒绝或已拒绝过
			uni.showModal({
				title: '位置权限申请',
				content: '需要获取您的位置信息来显示宠物定位，请允许位置权限',
				success: (tip) => {
					if (tip.confirm) {
						// 用户同意，打开设置页面
						uni.openSetting({
							success: (data) => {
								if (data.authSetting['scope.userLocation'] === true) {
									uni.showToast({
										title: '授权成功',
										icon: 'success'
									});
									// 重新获取位置
									getLocation();
								} else {
									uni.showToast({
										title: '授权失败，无法获取位置',
										icon: 'none'
									});
								}
							}
						});
					} else {
						uni.showToast({
							title: '需要位置权限才能使用定位功能',
							icon: 'none'
						});
					}
				}
			});
		}
	});
};

// 页面跳转函数
const push = (url) => {
	uni.navigateTo({
		url: url
	});
};
// 切换围栏状态
const toggleFenceStatus = async (status) => {
  if (!selectedFence.value) {
    uni.showToast({
      title: '请先选择围栏',
      icon: 'none'
    });
    return;
  }
  
  try {
    const data = {
      userId: userStore.userId,
      id: selectedFence.value.id,
      status: status // 0-关闭，1-开启
    };
    
    await closeFence(data);
    fenceStatus.value = status;
    
    uni.showToast({
      title: status == 1 ? '围栏已开启' : '围栏已关闭',
      icon: 'success'
    });
  } catch (e) {
    console.error('切换围栏状态失败:', e);
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'none'
    });
  }
};
onShow(() => {
	if (paging.value) {
        paging.value.reload();
    };
	getgj()
})
</script>
<style lang="scss" scoped>
.center_order_h {
	height: calc(100% - 70rpx)
}

.box_h {
	height: calc(100vh - 148px - 20rpx)
}

.rrr {
	font-family: D-DIN-PRO;
	font-size: 28rpx;
	font-weight: 500;
	line-height: 32rpx;
	text-align: center;
	letter-spacing: normal;
	color: #FF0000;
}

.wwww {
	font-family: PingFang SC;
	font-size: 24rpx;
	font-weight: normal;
	line-height: 32rpx;
	text-align: center;
	letter-spacing: normal;
	color: #999999;
}

.qqqq {
	font-family: PingFang SC;
	font-size: 20rpx;
	font-weight: normal;
	line-height: 24rpx;
	text-align: center;
	letter-spacing: normal;
	color: #999999;
}
</style>